#include "serverdev.h"
#include "ui_serverdev.h"
#include "company.h"
#include "task.h"
#include <QDebug>
#include <QDBusConnection>

ServerDev::ServerDev(QWidget *parent)
    : QWidget(parent),m_pTask(nullptr)
    , ui(new Ui::ServerDev)
{
    ui->setupUi(this);

    m_pThreadPool = QThreadPool::globalInstance();
    m_pThreadPool->setMaxThreadCount(10);

    m_pTimer = new QTimer();
    m_pTimer->setTimerType(Qt::PreciseTimer);
    connect(m_pTimer,&QTimer::timeout,this,&ServerDev::onTimeOut);
    m_pTimer->setInterval(5000);

    //初始化代理设备信息
    QList<QString> oidList;
    oidList.push_back("1.3.6.1.2.1.1.1.0");
    oidList.push_back("1.3.6.1.2.1.1.3.0");
    oidList.push_back("1.3.6.1.2.1.1.5.0");
    m_agentDevList.push_back(AgentDev("127.0.0.1","public",oidList));
    m_agentDevList.push_back(AgentDev("192.168.2.3","public",oidList));

    //new connection--------------------------
    QDBusConnection connection = QDBusConnection::sessionBus();
    //registe service
    if(!connection.registerService("company.recruitment")){
        //qDebug()<<connection.lastError().message();
        exit(1);
    }

    //registe object
    connection.registerObject("/company/path",&m_company,
                                   QDBusConnection::ExportAllContents);
}

void ServerDev::onTimeOut()
{
    for (AgentDev agentDev: m_agentDevList)
    {
        Task *pTask = new Task(agentDev.ip,agentDev.community,agentDev.oidList);
        connect(pTask,SIGNAL(sigOidContent(const QString &)),this,SLOT(sltOidContent(const QString &)));
        m_pThreadPool->start(pTask);
    }
}

void ServerDev::sltOidContent(const QString &strCnt)
{
    ui->get_textBrowser->append(strCnt + "\n");

    //数据分类入库db
}

ServerDev::~ServerDev()
{
    if(m_pTimer->isActive())
    {
        m_pTimer->stop();
        delete m_pTimer;
        m_pTimer = nullptr;
    }
    delete ui;
}

void ServerDev::on_getBtn_clicked()
{
    static bool bGet = false;
    bGet = !bGet;
    if(bGet && !m_pTimer->isActive())
    {
        m_pTimer->start();
        ui->getBtn->setText("停止获取");
    }
    else if(!bGet && m_pTimer->isActive())
    {
        m_pTimer->stop();
        ui->getBtn->setText("开始获取");
    }
}

void ServerDev::on_getClearBtn_clicked()
{
    ui->get_textBrowser->clear();
}

void ServerDev::on_setBtn_clicked()
{
    if(nullptr == m_pTask)
    {
        QList<QString> oidList;
        oidList.push_back("1.3.6.1.2.1.1.1.0");
        m_pTask = new Task("127.0.0.1","public",oidList);
    }

    m_pTask->setOidValue("666666");
}

void ServerDev::on_setClearBtn_clicked()
{
    ui->get_textBrowser->clear();
}
